#include <QStylePainter>
#include <QWindow>
#include <QHeaderView>
#include <QWebEngineScript>
#include <QWebEngineProfile>
#include <QWebEngineScriptCollection>
#include <QFile>
#include <QWebChannel>
#include <QHBoxLayout>
#include <core/FileSys.h>
#include "SWebWidget.h"
#include "WebReqHandler.h"
#include "SWebView.h"

SWebWidget::SWebWidget(const QString& title, const QString& url, QWidget* parent)
	: QWidget(parent)
	, m_title(title)
	, m_url(url)
	, m_webView(nullptr)
{
	setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	initCtrl();
}

SWebWidget::~SWebWidget()
{

}

void SWebWidget::setUrl(const QString& url)
{
	m_webView->load(QUrl(url.toUtf8().constData()));
}

void SWebWidget::initCtrl()
{
	QHBoxLayout* layout = new QHBoxLayout(this);       //垂直布局

	m_webView = new QbWebView(this);
	QWebChannel* channel = new QWebChannel(this);
	WebReqHandler* reqHandler = new WebReqHandler(this);
	channel->registerObject("QbWebHandler", (QObject*)reqHandler);
	m_webView->page()->setWebChannel(channel);
	connect(reqHandler, &WebReqHandler::result, this, &SWebWidget::onReqHandler, Qt::ConnectionType::QueuedConnection);

	QWebEngineScript script;
	QString scriptPath = ":/widgets/web/qwebchannel.js";
	QFile webChannel(scriptPath);
	webChannel.open(QIODevice::ReadOnly | QIODevice::Text);
	QString source = webChannel.readAll();
	webChannel.close();
	script.setSourceCode(source);
	script.setWorldId(QWebEngineScript::MainWorld);
	script.setInjectionPoint(QWebEngineScript::DocumentCreation);
	m_webView->page()->profile()->scripts()->insert(script);

	m_webView->load(QUrl(m_url.toUtf8().constData()));

	layout->addWidget(m_webView);
}

void SWebWidget::onReqHandler(int sid, QString res, QString cb)
{
	QString script = cb.isEmpty() ? QString("onQbResult(%1,%2)").arg(sid).arg(res) : QString("%1(%2)").arg(cb).arg(res);
	m_webView->page()->runJavaScript(script);
}
